package com.oyjd.framework.ui.webview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.oyjd.framework.log.MyLog;
import com.oyjd.framework.util.HttpNet;
import com.oyjd.framework.util.MsgShow;

/**
 * 定制webview
 * 
 * @author 欧建东
 * @email oyjd@163.com
 * 
 */
@SuppressLint("SetJavaScriptEnabled")
public class WebViewEx extends WebView {
	private CookieManager cookieManager;

	/**
	 * 构造函数
	 */
	public WebViewEx(Context context) {
		super(context);
		init(context);
	}

	/**
	 * 构造函数
	 * 
	 * @param context
	 * @param attrs
	 */
	public WebViewEx(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	/**
	 * 构造函数
	 * 
	 * @param context
	 * @param attrs
	 * @param defStyle
	 */
	public WebViewEx(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	/**
	 * 初始化
	 */
	private void init(Context context) {
		CookieSyncManager.createInstance(context);
		cookieManager = CookieManager.getInstance();
		//
		WebSettings setting = this.getSettings();
		setting.setJavaScriptEnabled(true);// 可用JS
		setting.setSupportZoom(true); // 设置可以支持缩放
		setting.setBuiltInZoomControls(true); // 设置出现缩放工具
		this.setScrollBarStyle(0);// 滚动条风格，为0就是不给滚动条留空间，滚动条覆盖在网页上
		this.setWebViewClient(new WebViewClient() {
			public void onPageFinished(WebView paramWebView, String paramString) {
				super.onPageFinished(paramWebView, paramString);
//				WebView.disablePlatformNotifications();
			}
		});
		this.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {// 载入进度改变而触发
				if (progress == 100) {
					// 如果全部载入,隐藏进度对话框
					MsgShow.cancleProgressDialog();
				}
				super.onProgressChanged(view, progress);
			}
		});
	}

	/**
	 * 普通加载url
	 */
	public void loadUrl(String url) {
		super.loadUrl(url);
		MyLog.d("HttpNet", "WebViewEx url=" + url);
	}

	/**
	 * webview加载url,包含注入session
	 * 
	 * @param url
	 */
	public void loadUrlEx(final String url) {
		MsgShow.showProgressDialog(getContext());
//		WebView.enablePlatformNotifications();
		String session = HttpNet.session;
		if (null != session) {
			cookieManager.setCookie(url, session);
			CookieSyncManager.getInstance().sync();
		}
		new Thread() {
			public void run() {
				loadUrl(url);// 载入网页
			}
		}.start();
	}

}
